/*
 * Copyright (c) 2018-2028 兰州安众信息科技有限公司 All Rights Reserved.
 * ProjectName: 甘肃九建OA系统
 */

package com.book.manager.security;


import com.book.manager.mapper.RoleMapper;
import com.book.manager.mapper.UserMapper;
import com.book.manager.model.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class MyUserDetailsService implements UserDetailsService {
    Logger log = LoggerFactory.getLogger(MyUserDetailsService.class);

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.book.manager.model.User userEntity = null;
        try {
            userEntity = userMapper.findUserWithUserNo(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户名：" + username + "不存在！");
        }
        String password = userEntity.getPwd();

        Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
        Iterator<Role> iterator = roleDao.listRoleWithUser(userEntity.getUserNo()).iterator();
        while (iterator.hasNext()) {
            collection.add(new SimpleGrantedAuthority(iterator.next().getRoleCode()));
        }

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.addAll(collection);
//        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");
//        grantedAuthorities.add(grantedAuthority);
        return new User(userEntity.getUserName(), userEntity.getPwd(), grantedAuthorities);

    }

}
